﻿using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using ZilLion.Service.Core.ConfigManager.Manager;

namespace ZilLion.Service.Core.DapperWrapper.SqlServer
{
    public class DefaultContext : IDbContext
    {
        /// <summary>
        /// </summary>
        public virtual string SystemDataConnectionString
            => ZilLionConfigurationManager.GetConfigInstance<DapperConfig>().DefaultConnection;

        public virtual IDbConnection GetConnection()
        {
            var connectionString = FomartConnectionString();
            if (!connectionString.IsNotNullOrEmpty()) return null;
            var connection = new SqlConnection(connectionString);

            return connection;
        }

        public virtual string ContextName => "DefaultSource";


        protected virtual string FomartConnectionString()
        {
            if (SystemDataConnectionString.IsNullOrEmpty())
                return null;

            var appname = Process.GetCurrentProcess().ProcessName;
            var builder = new SqlConnectionStringBuilder(SystemDataConnectionString)
            {
                ApplicationName = appname
            };
            return builder.ToString();
        }
    }
}